package com.faxsun.tools;

import java.util.ArrayList;
import java.util.List;

/**
 * admin分页工具
 * 
 * @author Zhilin
 * @since 2015/8/12
 */
public class PageUtils {
	/**
	 * 默认页显示大小
	 */
	public static final int DEFAULT_PAGE_SIZE = 50;
	public static final int DEFAULT_PAGE_COUNT = 10;

	@Deprecated
	public static List<Page> pageWrapper(int totalSize, int startIndex) {
		List<Page> pages = new ArrayList<Page>();
		int count = pageCount(totalSize);
		for (int i = 0; i < count; i++) {
			Page page = new Page();
			page.setStartIndex(i * DEFAULT_PAGE_SIZE + 1);
			page.setEndIndex((i + 1) * DEFAULT_PAGE_SIZE);
			if (startIndex == page.getStartIndex()
					|| (startIndex == 0 && page.getStartIndex() == 1)) {
				page.setCurrent(true);
			}
			page.setPage(i + 1);
			pages.add(page);

		}
		return pages;
	}

	public static Pagination defaultPageWrapper(int totalSize, int startIndex,
			int displaySize) {
		Pagination pagination = new Pagination();
		int currentPage = startIndex / DEFAULT_PAGE_SIZE + 1;
		int totalPages = pageCount(totalSize);
		int index = currentPage / displaySize
				+ (currentPage % displaySize == 0 ? 0 : 1);
		int start = (index - 1) * displaySize + 1;
		int end = index * displaySize;
		if (end >= totalPages) {
			end = totalPages;
		}
		if (currentPage == 1) {
			pagination.setPrevPage(null);
		} else {
			Page prevPage = new Page();
			int idx = currentPage - 1;
			prevPage.setStartIndex((idx - 1) * DEFAULT_PAGE_SIZE);
			prevPage.setEndIndex(idx * DEFAULT_PAGE_SIZE-1);
			pagination.setPrevPage(prevPage);
		}
		if (currentPage >= totalPages) {
			pagination.setNextPage(null);
		} else {
			Page nextPage = new Page();
			int idx = currentPage + 1;
			nextPage.setStartIndex((idx - 1) * DEFAULT_PAGE_SIZE );
			nextPage.setEndIndex(idx * DEFAULT_PAGE_SIZE-1);
			pagination.setNextPage(nextPage);
		}
		pagination.setPages(getPageList(start, end, currentPage));
		return pagination;
	}

	private static int pageCount(int totalSize) {
		return totalSize / DEFAULT_PAGE_SIZE
				+ (totalSize % DEFAULT_PAGE_SIZE == 0 ? 0 : 1);
	}

	private static List<Page> getPageList(int start, int end, int currentPage) {
		List<Page> pages = new ArrayList<Page>();
		for (; start <= end; start++) {
			Page page = new Page();
			page.setStartIndex((start - 1) * DEFAULT_PAGE_SIZE);
			page.setEndIndex(start * DEFAULT_PAGE_SIZE-1);
			page.setCurrent(currentPage == start);
			page.setPage(start);
			pages.add(page);
		}
		return pages;
	}

}
